import os
import sys
import hashlib

from django.conf import settings

CONF_DIR = lambda *dirs: os.path.join(os.path.abspath(os.path.dirname(__file__)), *dirs)
BASE_DIR = CONF_DIR('')
DIR_AT_ROOT = lambda *dirs: os.path.join(os.path.abspath(BASE_DIR), *dirs)

DEBUG = os.environ.get('DEBUG', 'on') == 'on'

SECRET_KEY = os.environ.get('DJ_SECRET_KEY', '{{ secret_key }}')

ALLOWED_HOSTS = os.environ.get('ALLOWED_HOSTS',
                               'a8xujr,localhost').split(',')

settings.configure(
    DEBUG = DEBUG,
    SECRET_KEY = SECRET_KEY,
    ALLOWED_HOSTS = ALLOWED_HOSTS,
    ROOT_URLCONF = __name__,
    MIDDLEWARE_CLASSES = (
        'django.middleware.common.CommonMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
    ),
    INSTALLED_APPS = (
        'django.contrib.staticfiles',
    ),
    TEMPLATE_DIRS = (
        DIR_AT_ROOT("templates"),
    ),
    STATICFILES_DIRS =(
        DIR_AT_ROOT('static'),
    ),
    STATIC_URL = '/static/',
)

from io import BytesIO
from PIL import Image, ImageDraw

from django import forms
from django.conf.urls import url
from django.core.wsgi import get_wsgi_application
from django.http import HttpResponse, HttpResponseBadRequest
from django.shortcuts import render, render_to_response
from django.template import Context, RequestContext
from django.core.cache import cache
from django.core.urlresolvers import reverse

class ImageForm(forms.Form):
    """Form to validate requested placeholder image."""
    height = forms.IntegerField(min_value=1, max_value=2000)
    width = forms.IntegerField(min_value=1, max_value=2000)

    def generate(self, image_format='PNG'):
        """Generate an image of the given type and return as raw bytes."""
        height = self.cleaned_data['height']
        width = self.cleaned_data['width']
        key = '{}.{}.{}'.format(width, height, image_format)
        content = cache.get(key)
        if content is None:
            image = Image.new('RGB', (width, height))
            draw = ImageDraw.Draw(image)
            text = '{} X {} ({})'.format(width, height, image_format)
            ##print text
            textwidth, textheight = draw.textsize(text)
            if textwidth < width and textheight < height:
                texttop = (height - textheight) // 2
                textleft = (width - textwidth) // 2
                draw.text((textleft, texttop), text, fill=(255,55,155))
            content = BytesIO()
            image.save(content, image_format)
            content.seek(0)
            cache.set(key, content, 60 * 60)
        return content


def placeholder(request, width, height):
    form = ImageForm({'height': height, 'width': width})
    if form.is_valid():
        image = form.generate()
        return HttpResponse(image, content_type="image/png")
    else:
        return HttpResponseBadRequest('Invalid Image Request')

def index_old(request):
    ##return HttpResponse('''<form method="POST" action="/placeholder">
    # {% csrf_token %}
    # <input type="text" name="height" id="height">
    # <input type="text" name="width" id="width">
    # <input type="submit" value="OK">
    # </form>''')
    return render_to_response('hello/index.html')

def index(request):
    example = reverse('placeholder', kwargs={'width': 150, 'height': 200})
    content = {
        'example': request.build_absolute_uri(example)
    }
    return render(request, 'hello/index.html', content)

def testpost(request):
    ##return HttpResponse('''<form method="POST" action="/placeholder">
    # {% csrf_token %}
    # <input type="text" name="height" id="height">
    # <input type="text" name="width" id="width">
    # <input type="submit" value="OK">
    # </form>''')
    return render_to_response('hello/testpost.html',
                              {},
                              RequestContext(request),
                          )

def gen_image(request):
    if request.method == "POST":
        return placeholder(request,
                           request.POST['width'],
                           request.POST['height'],
                       )

urlpatterns = (
    url(r'^$', index, name="index"),
    url(r'^testpost$', testpost, name="testpost"),
    url(r'^genimage$', gen_image, name="genimage"),
    url(r'^placeholder/(?P<height>\d+)x(?P<width>\d+)$',
        placeholder, name='placeholder'),
)

application = get_wsgi_application()

if __name__ == '__main__':
    from django.core.management import execute_from_command_line
    execute_from_command_line(sys.argv)
